package com.autologistics.socket.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogAppender {
	private static OutputStream os =null;
	private static SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD HH-mm-SS");
	
	static{
		try {
			File file = new File("AutoLogistics_log.txt");
			if(!file.exists()){
				System.out.println("is create successful? "+file.createNewFile());
			}
			System.out.println("file destnation:"+file.getAbsolutePath());
			os = new FileOutputStream(file, true);
			os.write("log start ...".getBytes());
			appendLog("collection information from runtime,design by mantou in mantoub.com");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//init error ,set os null
			os = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			os = null;
		}
	}

	public static synchronized void appendLog(String msg){
		if(os == null)
			return;
		Date date = new Date();
		
		try {
			os.write(("thread"+Thread.currentThread().getId()+" ").getBytes());
			os.write(sdf.format(date).getBytes());
			os.write(" : ".getBytes());
			os.write(msg.getBytes());
			os.write("\r\n".getBytes());
			os.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
